<template>
  <div class="course-selection">
      <div class="selection-toolbar">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-input-search
              placeholder="按课程名称、教师搜索"
              @search="handleSearch"
              enterButton
              v-model="searchValue"
            />
          </a-col>
          <a-col :span="8">
            <a-select
              style="width: 100%"
              placeholder="按课程类型筛选"
              @change="handleTypeChange"
              v-model="filterType"
            >
              <a-select-option value="all">全部课程</a-select-option>
              <a-select-option value="required">必修课</a-select-option>
              <a-select-option value="elective">选修课</a-select-option>
              <a-select-option value="public">公选课</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="8">
            <a-button-group>
              <a-button @click="refreshCourses">
                <a-icon type="sync" />刷新
              </a-button>
              <a-button type="primary" @click="showStrategyModal">
                <a-icon type="setting" />选课策略
              </a-button>
            </a-button-group>
          </a-col>
        </a-row>
      </div>

      <a-table
        :columns="columns"
        :dataSource="filteredCourses"
        rowKey="id"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <span slot="timeLocation" slot-scope="text, record">
          <div>{{ record.time }}</div>
          <div>{{ record.location }}</div>
        </span>

        <span slot="enrollment" slot-scope="text, record">
          {{ record.enrolled }}/{{ record.capacity }}
          <a-progress 
            :percent="Math.round((record.enrolled / record.capacity) * 100)" 
            :status="getProgressStatus(record)"
            size="small"
          />
        </span>

        <span slot="strategy" slot-scope="text, record">
          {{ text }}
          <a-tooltip :title="getStrategyDescription(record.strategy)">
            <a-icon type="question-circle" style="margin-left: 5px" />
          </a-tooltip>
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button 
            type="primary" 
            size="small"
            @click="handleSelect(record)"
            :disabled="!canSelect(record)"
          >
            选择
          </a-button>
          <a-tooltip v-if="!canSelect(record)" :title="getDisabledReason(record)">
            <a-icon type="question-circle" style="margin-left: 8px" />
          </a-tooltip>
        </span>
      </a-table>

      <strategy-setting-modal
        :visible="strategyModalVisible"
        :strategy="currentStrategy"
        @ok="handleStrategyOk"
        @cancel="handleStrategyCancel"
      />
  </div>
</template>

<script>
import StrategySettingModal from './modules/StrategySettingModal';

const columns = [
  {
    title: '课程编号',
    dataIndex: 'id',
    key: 'id',
    width: 100,
    sorter: true
  },
  {
    title: '课程名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
    sorter: true
  },
  {
    title: '学分',
    dataIndex: 'credit',
    key: 'credit',
    width: 80,
    sorter: true
  },
  {
    title: '任课教师',
    dataIndex: 'teacher',
    key: 'teacher',
    width: 120,
    sorter: true
  },
  {
    title: '时间/地点',
    key: 'timeLocation',
    scopedSlots: { customRender: 'timeLocation' },
    width: 180
  },
  {
    title: '选课人数',
    key: 'enrollment',
    scopedSlots: { customRender: 'enrollment' },
    width: 150
  },
  {
    title: '选课策略',
    dataIndex: 'strategy',
    key: 'strategy',
    scopedSlots: { customRender: 'strategy' },
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    width: 120
  }
];

export default {
  components: {
    StrategySettingModal
  },
  data() {
    return {
      columns,
      courses: [],
      loading: false,
      searchValue: '',
      filterType: 'all',
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50'],
        showTotal: total => `共 ${total} 门课程`
      },
      strategyModalVisible: false,
      currentStrategy: {},
      selectedCourses: []
    };
  },
  computed: {
    filteredCourses() {
      let filtered = this.courses;
      
      if (this.searchValue) {
        const lowerSearch = this.searchValue.toLowerCase();
        filtered = filtered.filter(c => 
          c.name.toLowerCase().includes(lowerSearch) || 
          c.teacher.toLowerCase().includes(lowerSearch)
        );
      }
      
      if (this.filterType !== 'all') {
        filtered = filtered.filter(c => c.type === this.filterType);
      }
      
      return filtered;
    }
  },
  created() {
    this.fetchCourses();
    this.fetchSelectedCourses();
  },
  methods: {
    fetchCourses(params = {}) {
      this.loading = true;
      // 模拟API调用
      setTimeout(() => {
        this.courses = this.generateMockCourses();
        this.filterCourses();
        this.pagination.total = this.filteredCourses.length;
        this.loading = false;
      }, 500);
    },
    
    generateMockCourses() {
      return [
        {
          id: "CS101",
          name: "计算机科学导论",
          credit: 3,
          teacher: "张明华",
          time: "周一 1-2节",
          location: "1号教学楼101",
          capacity: 60,
          enrolled: 45,
          strategy: "先选先得",
          type: "required",
          requirePrerequisite: false,
          prerequisite: ""
        },
        {
          id: "CS201",
          name: "数据结构与算法",
          credit: 4,
          teacher: "李伟",
          time: "周二 3-4节",
          location: "2号教学楼205",
          capacity: 50,
          enrolled: 50,
          strategy: "先选先得",
          type: "required",
          requirePrerequisite: true,
          prerequisite: "计算机科学导论"
        },
        {
          id: "CS301",
          name: "操作系统",
          credit: 4,
          teacher: "王建国",
          time: "周三 5-6节",
          location: "教学楼C301",
          capacity: 45,
          enrolled: 42,
          strategy: "选后抽签",
          type: "required",
          requirePrerequisite: true,
          prerequisite: "数据结构与算法"
        },
        {
          id: "CS401",
          name: "人工智能基础",
          credit: 3,
          teacher: "赵雪",
          time: "周四 7-8节",
          location: "教学楼D401",
          capacity: 40,
          enrolled: 38,
          strategy: "选课币",
          type: "elective",
          requirePrerequisite: true,
          prerequisite: "概率论与数理统计"
        },
        {
          id: "MA101",
          name: "高等数学(上)",
          credit: 5,
          teacher: "陈立",
          time: "周一 3-4节",
          location: "1号教学楼201",
          capacity: 80,
          enrolled: 75,
          strategy: "先选先得",
          type: "required",
          requirePrerequisite: false,
          prerequisite: ""
        },
        {
          id: "MA201",
          name: "线性代数",
          credit: 3,
          teacher: "刘芳",
          time: "周二 1-2节",
          location: "2号教学楼102",
          capacity: 60,
          enrolled: 55,
          strategy: "先选先得",
          type: "required",
          requirePrerequisite: false,
          prerequisite: ""
        },
        {
          id: "MA301",
          name: "概率论与数理统计",
          credit: 4,
          teacher: "孙强",
          time: "周三 3-4节",
          location: "教学楼C203",
          capacity: 50,
          enrolled: 48,
          strategy: "先选先得",
          type: "required",
          requirePrerequisite: true,
          prerequisite: "高等数学(上)"
        },
        {
          id: "CS501",
          name: "机器学习",
          credit: 3,
          teacher: "郑智能",
          time: "周二 7-8节",
          location: "教学楼E401",
          capacity: 35,
          enrolled: 32,
          strategy: "选课币",
          type: "elective",
          requirePrerequisite: true,
          prerequisite: "线性代数,概率论与数理统计"
        },
        {
          id: "CS601",
          name: "区块链技术",
          credit: 3,
          teacher: "钱链",
          time: "周三 7-8节",
          location: "教学楼F101",
          capacity: 30,
          enrolled: 25,
          strategy: "先选先得",
          type: "elective",
          requirePrerequisite: true,
          prerequisite: "数据结构与算法"
        },
      ];
    },
    
    fetchSelectedCourses() {
      // 模拟获取已选课程
      this.selectedCourses = [];
    },
    
    filterCourses() {
      let filtered = this.courses;
      
      // 按搜索条件过滤
      if (this.searchValue) {
        const lowerSearch = this.searchValue.toLowerCase();
        filtered = filtered.filter(c => 
          c.name.toLowerCase().includes(lowerSearch) || 
          c.teacher.toLowerCase().includes(lowerSearch)
        );
      }
      
      // 按类型过滤
      if (this.filterType !== 'all') {
        filtered = filtered.filter(c => c.type === this.filterType);
      }
      
      this.filteredCourses = filtered;
    },
    
    handleSearch(value) {
      this.searchValue = value;
      this.filterCourses();
    },
    
    handleTypeChange(value) {
      this.filterType = value;
      this.filterCourses();
    },
    
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination;
      // 实际项目中这里应该重新获取数据
      this.filterCourses();
    },
    
    refreshCourses() {
      this.fetchCourses();
    },
    
    canSelect(course) {
      // 检查是否可以选择该课程
      // 1. 检查是否已选
      if (this.selectedCourses.some(c => c.id === course.id)) {
        return false;
      }
      
      // 2. 检查时间冲突
      const hasConflict = this.selectedCourses.some(selected => {
        return selected.time === course.time;
      });
      if (hasConflict) {
        return false;
      }
      
      // 3. 检查先修课程要求
      if (course.requirePrerequisite) {
        // 这里应该检查学生是否已完成先修课程
        return false;
      }
      
      // 4. 检查人数是否已满
      if (course.strategy === '先选先得' && course.enrolled >= course.capacity) {
        return false;
      }
      
      return true;
    },
    
    getDisabledReason(course) {
      if (this.selectedCourses.some(c => c.id === course.id)) {
        return '您已选择该课程';
      }
      
      const hasConflict = this.selectedCourses.some(selected => {
        return selected.time === course.time;
      });
      if (hasConflict) {
        return '时间冲突';
      }
      
      if (course.requirePrerequisite) {
        return `需要先修课程: ${course.prerequisite}`;
      }
      
      if (course.strategy === '先选先得' && course.enrolled >= course.capacity) {
        return '人数已满';
      }
      
      return '不可选';
    },
    
    getProgressStatus(course) {
      const percent = (course.enrolled / course.capacity) * 100;
      if (percent >= 90) {
        return 'exception';
      } else if (percent >= 70) {
        return 'active';
      }
      return 'normal';
    },
    
    getStrategyDescription(strategy) {
      const descriptions = {
        '先选先得': '先到先得，选满即止',
        '选后抽签': '选课结束后抽签决定',
        '选课币': '使用选课币竞拍课程'
      };
      return descriptions[strategy] || '未知策略';
    },
    
    handleSelect(course) {
      this.$confirm({
        title: '确认选择该课程吗?',
        content: `课程名称: ${course.name}\n任课教师: ${course.teacher}\n上课时间: ${course.time}`,
        onOk: () => {
          // 1. 更新已选课程列表
          this.selectedCourses.push(course);
          
          // 2. 更新课程的已选人数
          const courseIndex = this.courses.findIndex(c => c.id === course.id);
          if (courseIndex !== -1) {
            // 使用Vue.set或直接赋值确保响应式更新
            this.$set(this.courses, courseIndex, {
              ...this.courses[courseIndex],
              enrolled: this.courses[courseIndex].enrolled + 1
            });
          }
          
          // 3. 显示成功消息
          this.$message.success(`成功选择课程: ${course.name}`);
          
          // 4. 触发事件(如果有需要)
          this.$emit('select', course);
          
          // 注意：如果使用计算属性filteredCourses，这里不需要手动调用filterCourses()
        },
        onCancel() {}
      });
    },
    
    showStrategyModal() {
      this.currentStrategy = {
        round: 'main',
        strategyType: 'firstCome',
        capacity: 50,
        crossGrade: false,
        crossMajor: false,
        courseLimit: 5,
        creditLimit: 25
      };
      this.strategyModalVisible = true;
    },
    
    handleStrategyOk(strategy) {
      this.strategyModalVisible = false;
      this.currentStrategy = strategy;
      this.$message.success('选课策略已更新');
    },
    
    handleStrategyCancel() {
      this.strategyModalVisible = false;
    }
  }
};
</script>

<style scoped>
.course-selection {
  margin: 0;
  padding:20px;
}
.selection-toolbar {
  margin-bottom: 16px;
}
</style>